from manim import *

class TriangleInequality(Scene):
    def construct(self):
        # 创建三角形 ABC
        A = np.array([-2, -1, 0])
        B = np.array([2, -1, 0])
        C = np.array([1, 2, 0])
        
        triangle_ABC = Polygon(A, B, C, color=BLUE)
        
        # 创建辅助点 D，使得 BD = BC
        BC_length = np.linalg.norm(B - C)
        D = B + (B - A) / np.linalg.norm(B - A) * BC_length  # D 点的位置，使得 BD = BC
        
        line_AD = Line(A, D, color=GREEN)
        line_CD = Line(C, D, color=GREEN)
        
        # 标记点
        point_A = Dot(A).set_color(RED)
        point_B = Dot(B).set_color(RED)
        point_C = Dot(C).set_color(RED)
        point_D = Dot(D).set_color(RED)
        
        label_A = MathTex("A").next_to(point_A, DOWN)
        label_B = MathTex("B").next_to(point_B, DOWN)
        label_C = MathTex("C").next_to(point_C, UP)
        label_D = MathTex("D").next_to(point_D, DOWN)

        # 显示三角形和点
        self.play(Create(triangle_ABC))
        self.play(FadeIn(point_A, point_B, point_C))
        self.play(Write(label_A), Write(label_B), Write(label_C))
        
        # 显示点 D 和辅助线
        self.play(Create(line_AD), Create(line_CD))
        self.play(FadeIn(point_D))
        self.play(Write(label_D))

        # 标记等腰三角形
        brace_BD = Brace(Line(B, D), DOWN)
        label_BD = brace_BD.get_text("BD = BC")
        self.play(Create(brace_BD), Write(label_BD))

        self.wait(1)

        # 解释角 BCD = 角 BDC
        angle_BCD = Angle(Line(C, B), Line(C, D), color=YELLOW)
        angle_BDC = Angle(Line(D, C), Line(D, B), color=YELLOW)
        self.play(Create(angle_BCD), Create(angle_BDC))
        
        label_angle_equal = MathTex(r"\angle BCD = \angle BDC").to_edge(DOWN * 3)
        self.play(Write(label_angle_equal))

        self.wait(1)

        # 标记角 ACD
        angle_ACD = Angle(Line(C, A), Line(C, D),radius=0.6, color=RED)
        self.play(Create(angle_ACD))

        label_angle_bigger = MathTex(r"\angle ACD > \angle BDC").next_to(label_angle_equal, DOWN)
        self.play(Write(label_angle_bigger))   

        self.wait(1)  

        # 添加说明，三角形中，较大的角对应较长的边，因此，AD > AC，而 AD = AB + BD
        explanation = MathTex(r"\text{In } \triangle ACD, \text{ } AD > AC \text{ and } AD = AB + BD = AB + BC").next_to(label_angle_bigger, DOWN)
        self.play(Write(explanation))

        # 标记 AB + BC > AC
        inequality = MathTex("AB + BC > AC").to_edge(UP)
        self.play(Write(inequality))

        # 结束动画
        self.wait(2)